<script setup lang="ts">
import { debounce } from 'ts-debounce-throttle'
import type { NitroFetchRequest } from 'nitropack'

const {
  url,
  valueKey = 'id',
  labelKey = 'name',
  searchKey = 'name',
  subLabelKey,
  defaultList = [],
  pagination = true,
  extraParam = {}
} = defineProps<{
  url: NitroFetchRequest
  defaultList?: any[]
  valueKey?: string
  labelKey?: string
  subLabelKey?: string
  searchKey?: string
  pagination?: boolean
  extraParam?: object
}>()

const PAGE_SIZE = 100

const params = ref({
  pageNum: 1,
  pageSize: PAGE_SIZE,
  enable: 1,
  [searchKey]: '',
  ...extraParam
})

const { emitFormBlur, emitFormFocus, emitFormChange } = useFormField()

const list = ref<any[]>([])

const handleChange = debounce(async function (searchVal: string) {
  params.value[searchKey] = searchVal
  params.value.pageNum = 1
  await loadList()
}, 500)

async function loadList() {
  // if (pagination) {
  //   const { data } = await get<InfraPagerResEntity<any>>(url, params.value)
  //   list.value = data.value.list
  // } else {
  //   const { data } = await get<any>(url, params.value)
  //   list.value = data.value
  // }
}

async function handleOpen(visible: boolean) {
  if (visible) {
    list.value = []
    params.value.pageNum = 1
    params.value[searchKey] = ''
    await loadList()
  }
}

watch(
  () => defaultList,
  (val) => {
    list.value = val
  }
)
</script>

<template>
  <USelectMenu
    :ui="{ base: 'w-full' }"
    :valueKey="valueKey"
    :label-key="labelKey"
    :items="list"
    placeholder="请选择"
    v-bind="$attrs"
    :search-input="{
      placeholder: '输入文字过滤...',
      icon: 'i-mingcute:search-2-line'
    }"
    :resetSearchTermOnSelect="false"
    @update:searchTerm="handleChange"
    @update:open="handleOpen"
    @focus="emitFormFocus"
    @blur="emitFormBlur"
    @change="emitFormChange"
  >
    <template #item-label="{ item }">
      <div class="inline-flex items-baseline gap-1.5">
        <span v-if="labelKey">{{ item[labelKey] }}</span>
        <span class="text-xs text-gray-400" v-if="subLabelKey">{{ item[subLabelKey] }}</span>
      </div>
    </template>
  </USelectMenu>
</template>
